﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExplosionDamage : MonoBehaviour
{
    public float destroySlefTime = 2.0f;    //自毁时间
    public float explosionRudius = 5.0f;    //爆炸影响半径
    public float explosionDamage = 500f;    //爆炸产生的伤害
    public float explosionPower = 5000f;    //爆炸产生的爆发力
    public Collider[] hitCollicers;
    private void Awake()
    {
        Destroy(gameObject, destroySlefTime);
    }

    // Start is called before the first frame update
    void Start()
    {
        //爆炸中心位置
        Vector3 explosionPosition = transform.position;

        //爆炸中心内所有具有碰撞网格的碰撞体（可以不具有刚体）,放到数组中
        hitCollicers = Physics.OverlapSphere(explosionPosition,explosionRudius);

        //计算伤害
        for(int i=0;i<hitCollicers.Length;i++)
        {
            //返回碰撞体与爆炸中心最近的点
            Vector3 closestPoint = hitCollicers[i].ClosestPointOnBounds(explosionPosition);
            //计算距离
            float distance = Vector3.Distance(closestPoint, explosionPosition);
            //计算伤害点数的百分比，随距离增加而降低
            float hitPiontPrecentage = 1.0f - Mathf.Clamp01(distance / explosionRudius);
            //计算最后的伤害点数
            float damage = hitPiontPrecentage * explosionDamage;
            //向受影响的碰撞体发送碰撞消息,调用该物体的减血方法
            hitCollicers[i].SendMessageUpwards("TankDamege", damage,SendMessageOptions.DontRequireReceiver);
            //如果碰撞体上有刚体，施加一个爆炸力
            if(hitCollicers[i].GetComponent<Rigidbody>()!=null)
            {
                hitCollicers[i].GetComponent<Rigidbody>().AddExplosionForce(explosionPower, explosionPosition, explosionRudius);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
